
/*window.alert = function(msg){
	Modal.alert({msg:msg});
};*/

$.getUrlParam = function (name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]); return null;
};
//生成唯一编号
function newGuid()  
{  
    var guid = "";  
    for (var i = 1; i <= 32; i++){  
      var n = Math.floor(Math.random()*16.0).toString(16);  
      guid +=   n;  
      if((i==8)||(i==12)||(i==16)||(i==20))  
        guid += "-";  
    }  
    return guid;      
}
/*选项索引键值对*/
var optionsKey={
		"1":"A","2":"B","3":"C","4":"D","5":"E","6":"F","7":"G","8":"H","9":"I","10":"J","11":"K","12":"L","13":"M","14":"N","15":"O","16":"P","17":"Q","18":"R","19":"S","20":"T","21":"U","22":"V","23":"W","24":"X","25":"Y","26":"Z"
};
/* 创建编辑器  */
var E = window.wangEditor;
var editor = new E('#content-toolbar','#content');
/*
 * 初始化
 *  */
$(function() {
	
	//初始化编辑器
	editor.customConfig.uploadImgMaxSize = 6 * 1024 * 1024;
	editor.customConfig.uploadImgMaxLength = 5;
	editor.customConfig.uploadFileName = 'myFileName';
	editor.customConfig.uploadImgHeaders = {
	       'Accept' : 'multipart/form-data'
	   };
	editor.customConfig.menus = [//定义菜单
		'image'
	];
	editor.customConfig.uploadImgServer = '/exam/files/upload';
	editor.customConfig.showLinkImg = false;
	editor.create();
	
    $(".selectpicker").selectpicker({  
        noneSelectedText : '请选择'  
        });  
  
        $(window).on('load', function() {
        	$('.selectpicker').selectpicker('refresh');
        	$('.selectpicker').selectpicker('val', '');
        });  
  
        // 下拉数据加载
    $.ajax({
        type : 'get',  
        url :"teacher/getSubjects",  
        dataType : 'json',  
        success : function(datas) {// 返回list数据并循环获取
            var select = $("#slpk");  
            for (var i = 0; i < datas.length; i++) {  
                select.append("<option value='"+datas[i].id+"'>"  
                        + datas[i].name + "</option>");  
            }
            $('.selectpicker').selectpicker('refresh');
            $('.selectpicker').selectpicker('val', '');
            
            //加载完选项再加载编辑信息
            var id = $.getUrlParam('id');
            if(id!=null&&id!=""){
            	//加载信息
            	$.ajax({
            		url:'single/findOne',
            		type:'post',
            		dataType:'json',
            		data:{id:id},
            		success:function(data){
            			if(null!=data){
            				//加载题目信息
            				$('#id').val(data.id);
            				$('#num').val(data.num);
            				if(data.subject!=null)
            					$('.selectpicker').selectpicker('val', data.subject.id);
            				editor.txt.html(data.title);
            				var length = Object.keys(data.options).length;
            				for(var i=0;i<length;i++){
            					var option = data.options[optionsKey[i+1]];
            					var optionHtml = "";
            					optionHtml += '<div class="form-group option-item">'+
            								'<input type="hidden" name="option_id" value='+option.id+'>'+
            								'<input type="hidden" name="option_num" value="'+option.num+'">'+
            								'<label class="col-sm-1 control-label"><span class="option-index">'+optionsKey[i+1]+'</span>&nbsp;';
            								if(data.answer.id==option.id)
            									optionHtml += '<input checked ';
            								else
            									optionHtml += '<input ';
            					optionHtml += 'required type="radio" name="answerKey" value="'+optionsKey[i+1]+'"></label>'+
            								'<div class="col-sm-10">'+
            									'<div id="toolbar'+optionsKey[i+1]+'" class="toolbar">'+
            									'</div>'+
            									'<div id="text'+optionsKey[i+1]+'" class="text">'+
            								    '</div>'+
            								 '</div>'+
            							'</div>';
            					$("#option-container").append(optionHtml);
            					var optionsE = window.wangEditor;
            					var editorO = new optionsE('#toolbar'+optionsKey[i+1],'#text'+optionsKey[i+1]);
            					editorO.customConfig.uploadImgMaxSize = 6 * 1024 * 1024;
            					editorO.customConfig.uploadImgMaxLength = 5;
            					editorO.customConfig.uploadFileName = 'myFileName';
            					editorO.customConfig.uploadImgHeaders = {
            					       'Accept' : 'multipart/form-data'
            					   };
            					editorO.customConfig.menus = [//定义菜单
            						'image',
            						'quote'
            					];
            					editorO.customConfig.uploadImgServer = '/exam/files/upload';
            					editorO.customConfig.showLinkImg = false;
            					editorO.create();
            					editorO.txt.html(option.content);
            				}
            			}else{
            				window.location.href="/exam/tch_single";
            			}
            		},
            		error:function(){
            			Modal.alert({msg:'出错！'});
            			window.location.href="/exam/tch_single";
            		}
            	});
            }
            
        }
    });
    
    
    
});
/*填空宽度控制*/
var textWidth = function(text){ 
    var sensor = $('<pre>'+ text +'</pre>').css({display: 'none'}); 
    $('body').append(sensor); 
    var width = sensor.width();
    sensor.remove();
    return width;
};
function changeText(obj){
    $(obj).width(textWidth($(obj).val())+30);
}

/*添加选项事件*/
function addOption(){
	//1 获取到已存在的选项
	var options = $("#option-container").find(".option-item");
	//当前选项索引optionsKey[options.length+1]
	var html = "";
	html += '<div class="form-group option-item">'+
				'<input type="hidden" name="option_id">'+
				'<input type="hidden" name="option_num">'+
				'<label class="col-sm-1 control-label"><span class="option-index">'+optionsKey[options.length+1]+'</span>&nbsp;<input required type="radio" name="answerKey" value="'+optionsKey[options.length+1]+'"></label>'+
				'<div class="col-sm-10">'+
					'<div id="toolbar'+optionsKey[options.length+1]+'" class="toolbar">'+
					'</div>'+
					'<div id="text'+optionsKey[options.length+1]+'" class="text"> <!--可使用 min-height 实现编辑区域自动增加高度-->'+
				    '</div>'+
				 '</div>'+
			'</div>';
	$("#option-container").append(html);
	
	var optionsE = window.wangEditor;
	var editorO = new optionsE('#toolbar'+optionsKey[options.length+1],'#text'+optionsKey[options.length+1]);
	editorO.customConfig.uploadImgMaxSize = 6 * 1024 * 1024;
	editorO.customConfig.uploadImgMaxLength = 5;
	editorO.customConfig.uploadFileName = 'myFileName';
	editorO.customConfig.uploadImgHeaders = {
	       'Accept' : 'multipart/form-data'
	   };
	editorO.customConfig.menus = [//定义菜单
		'image',
		'quote'
	];
	editorO.customConfig.uploadImgServer = '/exam/files/upload';
	editorO.customConfig.showLinkImg = false;
	editorO.create();
	
}
/*删除选项*/
function deleteOption(obj){
	/*if(confirm("确定要删除选项?")){
		var item = $(obj).parents('.option-item');
		var prev = item.prevAll('.option-item');
		var afte = item.nextAll('.option-item');
		for(var i=0;i<afte.length;i++){
			//删除前设置下级兄弟元素的索引
			var option_index = $(afte[i]).find('.option-index');
			$(option_index[0]).text(optionsKey[prev.length+i+1]);
			//设置id
			var toolbar = $(afte[i]).find('.toolbar');
			var text = $(afte[i]).find('.text');
			$(toolbar).prop("id","toolbar"+optionsKey[prev.length+i+1]);
			$(text).prop("id","text"+optionsKey[prev.length+i+1]);
		}
		//删除该选项
		$(item).remove();
	}*/
	Modal.confirm(
		    {
		        msg: "确定要删除选项？"
		    })
		    .on( function (e) {
		        if(e){
		        	var item = $(obj).parents('.option-item');
		    		var prev = item.prevAll('.option-item');
		    		var afte = item.nextAll('.option-item');
		    		for(var i=0;i<afte.length;i++){
		    			//删除前设置下级兄弟元素的索引
		    			var option_index = $(afte[i]).find('.option-index');
		    			$(option_index[0]).text(optionsKey[prev.length+i+1]);
		    			//设置id
		    			var toolbar = $(afte[i]).find('.toolbar');
		    			var text = $(afte[i]).find('.text');
		    			$(toolbar).prop("id","toolbar"+optionsKey[prev.length+i+1]);
		    			$(text).prop("id","text"+optionsKey[prev.length+i+1]);
		    		}
		    		//删除该选项
		    		$(item).remove();
		        }
		    });
}
/* 单选题信息提交 */
$("#singleForm").submit(function(event){
	/*private Long id;
	private String title;
	private String num;
	private Subject subject;
	private Map<String, Options> options = new HashMap<String, Options>();
	private Options answer;*/
	var single = {};
	var options = {};
	var answer = {};
	
	var id = $('#id').val();
	var num = $('#num').val();
	$(single).attr("id",id);
	$(single).attr("num",num);
	
	var subject = {};
	var subjectId = $('#slpk option:selected').val();
	$(subject).attr("id",subjectId);
	$(single).attr("subject",subject);
	
	//获取题干
	var title = editor.txt.html();
	if(title==null||title==""||title=="<p><br></p>"){
		Modal.alert({msg:'题干不能为空！'});
		return false;
	}
	$(single).attr("title",title);
	
	//获取选项
	var items = $('.option-item');
	if(items.length<=0){
		Modal.alert({msg:'请添加选项！'});
		return false;
	}
	for(var i=0;i<items.length;i++){
		var option_id = $(items[i]).find('input[name="option_id"]').val();
		var option_num = $(items[i]).find('input[name="option_num"]').val();
		
		if(option_num==""||option_num==null)
			option_num = newGuid();
		
		var input = $(items[i]).find('.w-e-text');
	
		var keyElement = $(items[i]).find('.option-index');
		var key = $(keyElement).text();
		if($(input[0]).html()==""||$(input[0]).html()=="<p><br></p>"){
			Modal.alert({msg:'选项的内容不能为空！'});
			return false;
		}
		var option = {};
		
		$(option).attr("id",option_id);
		$(option).attr("num",option_num);
		$(option).attr("content",$(input[0]).html());
		
		$(options).attr(key,option);
		console.log($("input[name='answerKey']:checked").val()+key)
		if($("input[name='answerKey']:checked").val()==key){
			answer = option;
			console.log(JSON.stringify(answer));
		}
	}
	$(single).attr("options",options);
	$(single).attr("answer",answer);
	
	//获取正确选项的key
	var answerKey = $("input[name='answerKey']:checked").val();
	
	var result = JSON.stringify(single);
	console.log(result)
	$.ajax({
		url:'single/saveOrUpdate',
		type:'post',
		dataType:'json',
		data:{single:result},
		success:function(data){
			alert(data.msg);
			if(data.success){
				window.location.href="/exam/tch_single_form";
			}
		},
		error:function(){
			Modal.alert({msg:'出错！'});
		}
	});
	
	return false;
});
function test(){
	var blank = {};
	var blanks = {};
	
	var id = $('#id').val();
	var num = $('#num').val();
	
	var inputs = $('.the-blank');
	for(var i=0;i<inputs.length;i++){
		$(blanks).attr((i+1),inputs[i].value);
	}
	console.log(JSON.stringify(blanks));
	
	
	
	var content = editor.txt.html();
	console.log(content);
	$("body").append(content);
	alert($('#slpk option:selected').val());
}
function test2(){
	window.location.href="/exam/tch_single_form";
}